<template>
  <div class="login-page">
    <div class="container d-flex  opacity-95 align-items-center position-relative py-5">
      <div class="card w-100 rounded ">
        <div class="card-body  p-0">
          <div class="row gx-0 align-items-stretch">
            <!-- Logo & Information Panel-->
            <div class="col-lg-6" style="">
              <div class="info  d-flex justify-content-center flex-column p-4 h-100">
                <div class="py-5">
                  <h1 class="display-6 text-white"><span class="fw-bold fs-1">JackPay -- </span><span class="fs-4">登录</span></h1>
                  <p class="fw-light mb-1">让支付更简单.....</p>
                </div>
              </div>
            </div>
            <!-- Form Panel    -->
            <div class="login-panel col-lg-6">
              <div class="d-flex align-items-center px-4 h-100">
                <form class="login-form py-5 w-100">
                  <div class="d-flex fs-6 minput-material-group mb-4 text-dark">
                    <div :class="{'active': loginMethod === 1}" class="col-6 h-100 text-center " @click="switchoverLoginMethod(1)">密码登录</div>
                    <div :class="{'active': loginMethod === 2}" class="col-6 h-100 text-center" @click="switchoverLoginMethod(2)">验证码</div>
                  </div>
                  <div class="input-material-group mb-3 col-10 mx-auto">
                    <input
                        v-model="loginFrom.account"
                        @keyup.enter="handleLoginSubmit"
                        class="input-material"
                        placeholder="输入邮箱 或 手机号"/>
                    <span v-if="vaildAccount === 1" class="hint-text">用户账号 或 邮箱 不能为空哦</span>
                  </div>

                  <div v-if="loginMethod === 1" class="input-material-group mb-3 col-10 mx-auto">
                    <div class="d-flex">
                      <input
                          v-model="loginFrom.pwd"
                          class="input-material"
                          @keyup.enter="handleLoginSubmit"
                          :type="showPassword === false ? 'text' : 'password'"
                          placeholder="输入密码">
                      <p @click="togglePassword" class="eye-button">
                        <span v-if="showPassword === false"><img src="https://cdn.iextend.top/pay/svg/preview-open.svg"></span>
                        <span v-if="showPassword === true"><img src="https://cdn.iextend.top/pay/svg/preview-close-one.svg"> </span>
                      </p>
                    </div>
                    <span v-if="vaildPwd == 1" class="hint-text">密码不能为空哦</span>
                  </div>

                  <div v-if="loginMethod === 2" class="input-material-group mb-3 col-10 mx-auto ">
                    <div class="d-flex">
                      <input
                          v-model="loginFrom.pwd"
                          class="input-material"
                          @keyup.enter="handleLoginSubmit"
                          placeholder="输入密码">
                      <NButton class="send-code-btn" color="#2F80ED" @click="getVerifyCodeBtn" :disabled="initSecond > 0">
                        <span v-if="initSecond == 0">验证码</span>
                        <span v-if="initSecond > 0">{{initSecond}}后重发</span>
                      </NButton>
                    </div>
                    <span v-if="vaildPwd == 1" class="hint-text">验证码不能为空哦</span>
                  </div>

                  <div class="input-material-group mb-2 col-6 mx-auto">
                    <NButton class="btnLogin w-100" color="#2F80ED" @click="handleLoginSubmit">登录</NButton>
                  </div>

                  <div class="input-material-group  col-10 mx-auto d-flex">
                    <p class="col-5">
                      <NButton class="w-100"  @click="handleLoginSubmit">Gitee登录</NButton>
                    </p>
                    <p class="col-2"></p>
                    <p class="col-5">
                      <NButton class="w-100"  @click="handleLoginSubmit">Github登录</NButton>
                    </p>
                  </div>

                  <div class="input-material-group  col-10 mx-auto d-flex">
                    <p class="col-5">
                      <NButton class="w-100"  @click="handleLoginSubmit">微信登录</NButton>
                    </p>
                    <p class="col-2"></p>
                    <p class="col-5">
                      <NButton class="w-100" @click="handleLoginSubmit">QQ登录</NButton>
                    </p>
                  </div>


                  <div class="input-material-group col-10 mx-auto">
                    <a class="text-sm text-paleBlue pull-right" href="/forget">忘记密码?</a>
                    <br>
                    <small class="text-gray-500">还没账号? </small>
                    <a class="text-sm text-paleBlue" href="/register">立即注册下</a>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import {  useNotification} from "naive-ui";
import { loginAPI, loginVerifyAPI, getVerifyCodeAPI} from "@/api";
import { useUserStore} from "@/store";
import { resultCodeNotify } from '@/utils/rest/notifyHint'
import { getCastCurrentDate } from '@/utils/time/timeUtils'

const hint = useNotification();
const userStore = useUserStore();
const router = useRouter();
const sendType = 3;

const loginFrom = ref({account: "", pwd: "", source: 0});

let loginMethod = ref(1)            // 默认登录方式 1: 账号 密码 2: 验证码登录
const vaildAccount = ref<number>(0);                           // 账号提示框
const vaildPwd = ref<number>(0) ;                               // 密码 或 验证码提示
const initSecond = ref<number>(0);

const contentHit = "发送";
const timer = ref<ReturnType<typeof setInterval> | null>(null); // 初始化计时器引用
const showPassword = ref<boolean>(true)                        // 是否显示密码


/**
 * 切换登录方式
 */
function switchoverLoginMethod(source: number) {
  vaildPwd.value = 0;
  vaildAccount.value = 0;
  loginMethod.value = source;
}

/**
 * 密码是否显示
 */
function togglePassword() {
  if (showPassword.value === false) {
    showPassword.value = true
  } else {
    showPassword.value = false
  }
}
/**
 * 初始化提示值
 */
function initHintParam(){
  vaildPwd.value = 0;
}


/**
 *  验证账号
 */
function vailAccountVerify() {
  if(loginFrom.value.account === '') {
    vaildAccount.value = 1;
    return true;
  }
  vaildAccount.value = 0;
  const emailRegex = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
  if (!emailRegex.test(loginFrom.value.account)) {
    loginFrom.value.source = 1;
  } else {
    loginFrom.value.source = 0;
  }
}

/**
 * 验证登录数据是否符合
 */
function vailLoginVerify() {
  initHintParam();
  let verifyCode = false;
  if (vailAccountVerify()) {
    verifyCode = verifyCode || true;
  }
  if (loginFrom.value.pwd === '') {
    vaildPwd.value = 1;
    verifyCode = verifyCode || true;
  }
  return verifyCode;
}


/**
 * 获取验证码
 */
async function getVerifyCodeBtn() {
  if (vailAccountVerify()) {
    return;
  }
  await getVerifyCodeAPI({
    account: loginFrom.value.account,
    source: loginFrom.value.source,
    type:  sendType
  }).then(res => {
    resultCodeNotify(hint,  "验证码发送", res)
    if (res.code === 200) {
      timerStart();
    }
  }).catch(error => {
    resultCodeNotify(hint,  "验证码发送", error)
  })
}

/**
 * 登录
 */
async function handleLoginSubmit() {
  if (vailLoginVerify()) {
    return true;
  }
  // 账号 和 密码 登录
  if (loginMethod.value === 1) {
    await loginAPI(loginFrom.value).then(res => {
      resultCodeNotify(hint,  "登录", res)
      if (res.code === 200) {
        const result:User.saveUserInfo = res.data
        result.userSetting.lastOneTime = getCastCurrentDate(result.userSetting.lastOneTime)
        userStore.saveLoginUserInfo(result)
        router.push("/dashboard/profile")
      }
    }).catch(error => {
      resultCodeNotify(hint,  "登录", error)
    })
  }
  // 账号 和 验证码登录
  if (loginMethod.value === 2) {
    await loginVerifyAPI(loginFrom.value).then(res => {
      resultCodeNotify(hint,  "登录", res)
      if (res.code === 200) {
        const result:User.saveUserInfo = res.data
        result.userSetting.lastOneTime = getCastCurrentDate(result.userSetting.lastOneTime)
        userStore.saveLoginUserInfo(result)
        router.push("/dashboard/profile")
      }
    }).catch(error => {
      resultCodeNotify(hint,  "登录", error)
    })
  }
}

/**
 * 倒计时
 */
function timerStart() {
  initSecond.value = 60;
  timer.value = setInterval(() => {
    if (initSecond.value > 0) {
      initSecond.value--;
    } else {
      clearInterval(timer.value);
    }
  }, 1000);
}

/**
 * 停止倒计时
 */
function stopTimer() {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
}

/**
 * 清空倒计时
 */
onUnmounted(() => {
  stopTimer(); // 在组件卸载时停止计时器
});


</script>

<style>
@import "../hooks/style/account.css";
</style>
